1 /*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.cache;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtCompatible;
23 import com.google.common.base.Function;
24 import com.google.common.base.Supplier;
25
26 import java.io.Serializable;
27 import java.util.Map;
28
29 /**
30 * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}.
31 *
32 * <p>Most implementations will only need to implement {@link #load}. Other methods may be
33 * overridden as desired.
34 *
35 * <p>Usage example: <pre> {@code
36 *
37 * CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
38 * public Graph load(Key key) throws AnyException {
39 * return createExpensiveGraph(key);
40 * }
41 * };
42 * LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);}</pre>
43 *
44 * @author Charles Fry
45 * @since 10.0
46 */
47 @GwtCompatible(emulated = true)
48 public abstract class CacheLoader<K, V> {
49 /**
50 * Constructor for use by subclasses.
51 */
52 protected CacheLoader() {}
53
54 /**
55 * Computes or retrieves the value corresponding to {@code key}.
56 *
57 * @param key the non-null key whose value should be loaded
58 * @return the value associated with {@code key}; <b>must not be null</b>
59 * @throws Exception if unable to load the result
60 * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
61 * treated like any other {@code Exception} in all respects except that, when it is caught,
62 * the thread's interrupt status is set
63 */
64 public abstract V load(K key) throws Exception;
65
66 /**
67 * Computes or retrieves the values corresponding to {@code keys}. This method is called by
68 * {@link LoadingCache#getAll}.
69 *
70 * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
71 * contain will be cached, but {@code getAll} will throw an exception. If the returned map
72 * contains extra keys not present in {@code keys} then all returned entries will be cached,
73 * but only the entries for {@code keys} will be returned from {@code getAll}.
74 *
75 * <p>This method should be overriden when bulk retrieval is significantly more efficient than
76 * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
77 * to {@link LoadingCache#get} if this method is not overriden.
78 *
79 * @param keys the unique, non-null keys whose values should be loaded
80 * @return a map from each key in {@code keys} to the value associated with that key;
81 * <b>may not contain null values</b>
82 * @throws Exception if unable to load the result
83 * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
84 * treated like any other {@code Exception} in all respects except that, when it is caught,
85 * the thread's interrupt status is set
86 * @since 11.0
87 */
88 public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
89 // This will be caught by getAll(), causing it to fall back to multiple calls to
90 // LoadingCache.get
91 throw new UnsupportedLoadingOperationException();
92 }
93
94 /**
95 * Returns a cache loader based on an <i>existing</i> function instance. Note that there's no need
96 * to create a <i>new</i> function just to pass it in here; just subclass {@code CacheLoader} and
97 * implement {@link #load load} instead.
98 *
99 * @param function the function to be used for loading values; must never return {@code null}
100 * @return a cache loader that loads values by passing each key to {@code function}
101 */
102 @Beta
103 public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
104 return new FunctionToCacheLoader<K, V>(function);
105 }
106
107 private static final class FunctionToCacheLoader<K, V>
108 extends CacheLoader<K, V> implements Serializable {
109 private final Function<K, V> computingFunction;
110
111 public FunctionToCacheLoader(Function<K, V> computingFunction) {
112 this.computingFunction = checkNotNull(computingFunction);
113 }
114
115 @Override
116 public V load(K key) {
117 return computingFunction.apply(checkNotNull(key));
118 }
119
120 private static final long serialVersionUID = 0;
121 }
122
123 /**
124 * Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
125 * to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
126 * implement {@link #load load} instead.
127 *
128 * @param supplier the supplier to be used for loading values; must never return {@code null}
129 * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
130 * key
131 */
132 @Beta
133 public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
134 return new SupplierToCacheLoader<V>(supplier);
135 }
136
137 private static final class SupplierToCacheLoader<V>
138 extends CacheLoader<Object, V> implements Serializable {
139 private final Supplier<V> computingSupplier;
140
141 public SupplierToCacheLoader(Supplier<V> computingSupplier) {
142 this.computingSupplier = checkNotNull(computingSupplier);
143 }
144
145 @Override
146 public V load(Object key) {
147 checkNotNull(key);
148 return computingSupplier.get();
149 }
150
151 private static final long serialVersionUID = 0;
152 }
153
154 static final class UnsupportedLoadingOperationException extends UnsupportedOperationException {}
155
156 /**
157 * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
158 *
159 * @since 11.0
160 */
161 public static final class InvalidCacheLoadException extends RuntimeException {
162 public InvalidCacheLoadException(String message) {
163 super(message);
164 }
165 }
166 }
167